from django import http
from django.shortcuts import render, redirect,reverse
from django.views import View
import re,json,logging
from django.contrib.auth import login, authenticate, logout
from django.db import DatabaseError
from django_redis import get_redis_connection
from django.contrib.auth.mixins import LoginRequiredMixin # 要限制用户访问,并响应HTML

from apps.users.models import User,Address
from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.utils.views import LoginRequiredJSONMixin # 要限制用户访问,并响应JSON
from celery_tasks.email.tasks import sen_verify_email
from apps.users.utils import generate_verify_url
from apps.goods.models import SKU
from apps.users.utils import check_verify_url
from apps.carts.utils import merge_cart_cookie_to_redis
# Create your views here.

logger = logging.getLogger("django")




##########用户商品浏览记录##################
class UserBrowseHistory(LoginRequiredJSONMixin,View):
    """我们设计的是只有登陆用户才能保存用户浏览记录"""

    def post(self,request):
        """保存用户商品浏览记录"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get("sku_id")

        # 校验参数
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.JsonResponse({"code":RETCODE.PARAMERR,"errmsg":"参数sku_id有误"})

        # 创建连接到redis3号库
        redis_conn = get_redis_connection("history")
        user = request.user
        # 创建管道
        pl = redis_conn.pipeline()

        # 先去重lrem
        # redis_conn.lrem("history_%s" % user.id,0,sku_id)
        pl.lrem("history_%s" % user.id,0,sku_id)
        # 在添加 lpush
        # redis_conn.lpush("history_%s" % user.id,sku_id)
        pl.lpush("history_%s" % user.id,sku_id)
        # 最后截取 ltrim
        # redis_conn.ltrim("history_%s" % user.id,0,4)
        pl.ltrim("history_%s" % user.id,0,4)
        # 执行管道
        pl.execute()

        # 响应结果
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK"})

    def get(self,request):
        """查询用户商品浏览记录"""
        # 创建连接到redis的对象
        redis_conn = get_redis_connection("history")
        # 查询redis的三号库中的浏览记录(sku_id)
        user = request.user
        # sku_ids = [b'sku_id5', b'sku_id4', b'sku_id3']
        sku_ids = redis_conn.lrange("history_%s" % user.id,0,-1)

        # 便利sku_ids取出sku_id ,并查询sku
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            # 将模型转字典
            skus.append({
                "id":sku.id,
                "name":sku.name,
                "price":sku.price,
                "default_image_url":sku.default_image.url
            })

        # 前端渲染页面: Vue使用json数据渲染
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","skus":skus})



##########修改密码################
class PasswordChangeView(LoginRequiredMixin,View):

    def get(self,request):

        return render(request,"user_center_pass.html")

    """修改密码"""
    def post(self,request):

        # 接收参数
        old_password = request.POST.get("old_password")
        new_password = request.POST.get("new_password")
        new_password2 = request.POST.get("new_password2")
        # 校验参数
        if not all([old_password,new_password,new_password2]):
            return http.HttpResponseForbidden("缺少必传参数")
        if not request.user.check_password(old_password):
            return render(request,"user_center_pass.html",{"origin_password_errmsg":"原始密码错误"})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')
        if new_password != new_password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return render(request, 'user_center_pass.html', {'change_password_errmsg': '修改密码失败'})

        # 清理状态保持信息
        logout(request)
        response = redirect(reverse("users:login"))
        response.delete_cookie("username")

        # 响应密码修改结果: 重定向到登陆界面
        return response


###########修改地址标题#################
class AddressTitleView(LoginRequiredJSONMixin, View):

    def put(self,request,address_id):
        """修改地址标题"""

        # 接收参数: 地址标题
        # json_dict = json.loads(request.body.decode())
        json_str = request.body.decode()
        json_dict = json.loads(json_str)

        title = json_dict.get("title")

        try:
            # 查询数据库
            address = Address.objects.get(id=address_id)

            # 设置新地址标题
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '修改地址标题失败'})

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改地址标题成功'})


###########设置默认地址#############
class AddressDefaultView(LoginRequiredJSONMixin,View):

    def put(self,request,address_id):
        """设置默认地址"""
        try:
            # 查询设置默认的地址
            address = Address.objects.get(id=address_id)

            # 设置为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({"code":RETCODE.DBERR,"errmsg":"设置默认地址失败"})

        return http.JsonResponse({"code": RETCODE.DBERR, "errmsg": "设置默认地址成功"})


#########修改和删除地址###################
class AddressUpdateDestroyView(LoginRequiredJSONMixin,View):
    """修改地址"""
    def put(self,request,address_id):
        # 接受参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get("receiver")
        province_id = json_dict.get("province_id")
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver,province_id,city_id,district_id,
                    place,mobile]):
            return http.HttpResponseForbidden("缺少必传参数")
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 判断地址是否存在,并更新地址
        try:
            address = Address.objects.get(id=address_id)
            address.user = request.user
            address.title = receiver
            address.receiver = receiver
            address.province_id = province_id
            address.city_id = city_id
            address.district_id = district_id
            address.place = place
            address.mobile = mobile
            address.tel = tel
            address.email = email
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址失败'})

        # 构造上下文
        address = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 返回结果
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"更新地址成功","address":address})


    def delete(self,request,address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置位True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({"code":RETCODE.DBERR,"errmsg":"删除地址失败"})

        return http.JsonResponse({"code": RETCODE.OK, "errmsg": "删除地址成功"})


#########新增地址####################
class AddressCreateView(LoginRequiredJSONMixin,View):
    """新增地址"""

    def post(self,request):
        """实现新增地址逻辑"""

        # 判断地址是否过多
        # 查询当前登录用户的未被逻辑删除的地址数量
        # count = Address.objects.filter(is_deleted=False).count()
        count = request.user.addresses.filter(is_deleted=False).count()
        if count >= 20:
            return http.JsonResponse({"code":RETCODE.THROTTLINGERR,"errmsg":"地址超过上限"})

        # 接受参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 核心逻辑:保存用户地址数据到数据库
        try:
            address = Address.objects.create(
                # user_id = request.user.id, # 对象赋值给外键属性名（对象对应对象）
                user = request.user,
                title = receiver,
                receiver =receiver,
                # province = province
                province_id = province_id, # id赋值给外键ｉｄ（id 对应 id)
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email

            )

            # 在新增地址之后,如果用户没有默认地址,就把当前的地址作为用户的默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})

        #将新增的地址数据响应到前端页面
        address = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,  # 关联查询(外键)
            "city": address.city.name,
            "district": address.district.name,# (外键)
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应结果
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"新增地址成功","address":address})



##########用户收货地址#################
class AddressView(LoginRequiredMixin, View):
    """用户收货地址"""

    def get(self, request):
        """提供收货地址页面"""
        # 查询当前登陆用户的所有的未被逻辑删除的收货地址, id_deleted
        addresses = request.user.addresses.filter(is_deleted=False)

        # 将字典列表转模型类,方便vue去把地址信息解析成vue可以识别的数据
        address_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }
            address_list.append(address_dict)

        # 构造上下文
        context = {
            "addresses":address_list,
            "default_address_id":request.user.default_address_id
        }

        # 渲染页面: vue渲染,因为收货地址页面需要局部刷新,所以需要将模板中的数据传递到vue
        return render(request, 'user_center_site.html',context)


#######设置验证邮箱的接口#################
class VerifyEmailView(View):
    """验证邮箱"""

    def get(self,request):
        """实现验证逻辑"""
        # 接受参数
        token = request.GET.get("token")

        # 校验参数
        if not token:
            return http.HttpResponseForbidden("缺少token")

        # 从token中提取要激活邮件的用户
        user = check_verify_url(token)
        if not user:
            return http.HttpResponseServerError("无效的token")

        # 将要激活邮件的用户的email_active 字段设置为True
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError("验证激活邮箱失败")

        # 响应结果:重定向到用户中心
        return redirect(reverse("users:info"))

##########添加邮箱################
class EmailView(LoginRequiredJSONMixin,View):
    """添加邮箱,只有登陆用户才能添加邮箱"""

    def put(self,request): # 因为修改,所以用put
        """实现添加邮箱逻辑"""
        # 接受参数: 请求体中JSON 用 body属性
        bytes_json_str = request.body # body:获取到最原始的bytes类型数据
        json_str = bytes_json_str.decode() # 把bytes类型的json字符串转成json字符串
        json_dict = json.loads(json_str) # 将json字符串转成字典
        email = json_dict.get("email")

        # 校验参数
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('参数email有误')

        # 添加邮箱: 将用户传入的email数据,保存到数据库 #数据库操作可能异常所以try
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({"code":RETCODE.DBERR,"errmsg":"添加邮箱失败"})


        # 发送验证邮件(需要使用celery解耦
        # verify_url = "邮箱验证链接"
        verify_url = generate_verify_url(request.user)
        # sen_verify_email.delay(email, "邮箱验证链接")
        sen_verify_email.delay(email, verify_url)


        # 响应结果
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"添加邮箱成功"})


######用户中心################
class UserInfoView(LoginRequiredMixin,View): # Mixin 封装了判断用户是否登陆的方法
    '''用户中心'''
    def get(self,request):
        """提供用户中心的页面"""
        # 查询当前登陆用户的基本信息
        login_user = request.user
        # username = login_user.username
        # mobile = login_user.mobile
        # email = login_user.email
        # email_acitve = login_user.email_acitve

        # 构造上下文 ,把后端的信息返回给模板让vue通过js渲染
        context = {
            'username': login_user.username,
            'mobile': login_user.mobile,
            'email': login_user.email,
            'email_active': login_user.email_active
        }
        # 使用上下文中的数据渲染模板
        return render(request,"user_center_info.html",context)


#######退出登陆###############
class LogoutView(View):
    def get(self,request): # fulash 清楚session信息也可以清楚
        # 清理状态保持信息
        logout(request)
        # 重定向到首页
        response = redirect(reverse("contents:index"))
        # 清理cookie中的用户名
        response.delete_cookie("username")
        # 响应结果
        return response


########用户登陆#############
class LoginView(View):
    def get(self,request):
        '''提供登陆页面'''
        return render(request,"login.html")

    def post(self,request):
        '''实现用户登陆逻辑'''
        # 接受参数
        username = request.POST.get("username")
        password = request.POST.get("password")
        remembered = request.POST.get("remembered")
        # 校验参数
        # 判断参数是否齐全 remembered 时可选的所以不用校验
        if not all([username, password]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入正确的用户名或手机号')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')

        # 认证用户
        user = authenticate(request,username=username,password=password)
        if not user:
            return render(request,"login.html",{"account_errmsg":"账号或密码错误"})

        # 状态保持
        login(request,user)
        # 根据用户是否记住登陆来设置状态保持的生命周期
        if remembered != "on":
            # 不记住登陆 浏览器会话结束后,状态保持销毁 set_expiry设置有效时间
            request.session.set_expiry(0)
        else:
            # 记住登陆 状态保持为两周  如果传入None默认两周
            request.session.set_expiry(None)

        # 登陆成功后重定向到其他页面
        next = request.GET.get("next")
        if next:
            # 跳转到对应的页面
            response = redirect(next)
        else:
            # 跳转到首页
            response = redirect(reverse("contents:index"))


        # 登陆成功之后,响应之前,用户名写入到 cookie
        # response = redirect(reverse("contents:index"))
        # response.set_cookie("key","value",max_age=3600*24*14)
        response.set_cookie("username",user.username,max_age=3600*24*14)

        # 合并购物车
        response = merge_cart_cookie_to_redis(request=request,user=user,response=response)

        # 响应结果
        return response


#########判断用户名是否重复注册############
class UsernameCountView(View):
    def get(self,request,username):
        # 查询用户名对应的记录个数
        '''
        :param  username: 判断是否重名的用户名
        :return:
        '''
        # 接受参数:函数中做了
        # 检验参数: 路径参数中正则做了
        # 实现核心逻辑: 查询用户名对应的个数
        # filter 返回的查询集,
        count = User.objects.filter(username=username).count()
        # 返回响应
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","count":count})


###########手机号重复注册################
class MobileCountView(View):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","count":count})


############用户注册####################
class RegisterView(View):

    def get(self,request):
        '''提供用户注册'''
        return render(request,"register.html")

    def post(self,request):
        '''实现用户注册逻辑'''
        # 1. 接收参数: 前端发送参数的方式决定了后端读取的方式  post 表单参数
        username = request.POST.get("username")
        password = request.POST.get("password")
        password2 = request.POST.get("password2")
        mobile = request.POST.get("mobile")

        # 校验手验证码
        sms_code_client = request.POST.get("sms_code")
        allow = request.POST.get("allow")

        # 2. 校验参数: 前后端校验逻辑要分开, 且逻辑要一致,后端校验逻辑大于等于前端校验逻辑
        # 判断参数是否齐全
        # all() 用来判断一些数据是否为空,将要判断的数据放在列表中作为参数.
        # 若任意一个数据为空,就返回False,全部都不为空就返回True
        if not all([username,password,password2,mobile,sms_code_client,allow]):
            return http.HttpResponseForbidden("缺少必传参数")
        # 判断用户名是否是5-20个字符
        if not re.match(r"^[a-zA-Z0-9_-]{5,20}$", username):
            return http.HttpResponseForbidden("参数username错误")
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')

        # 判断用户输入的和服务端储存的短信验证码是否一致
        # 连接redis...
        redis_conn = get_redis_connection("verify_code")
        # 从redis中取出服务器储存的验证码
        sms_code_server = redis_conn.get("sms_%s" % mobile)
        if not sms_code_server:
            return render(request,"register.html",{"sms_code_errmsg":"短信验证码失效"})
        # 因为sms_code_server 是bytes类型所以要解码解成字符串来做比较
        if sms_code_client != sms_code_server.decode():
            return render(request,"register.html",{"sms_code_errmsg":"短信验证码有误"})

        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        # 3. 实现核心逻辑: 保存用户注册数据
        # 第一种 密码无法加密,所以不选
        # user = User()
        # user.username = username
        # # ...
        # # 第二种 密码无法加密,所以不选00
        # user = User.objects.create(
        #     username=username
        #     #....
        # )

        # Django的用户认证系统提供的注册方法,set_password对密码进行加密所以选这个
        try:
           user = User.objects.create_user(username=username,
                                 password=password,
                                 mobile=mobile)
        except DatabaseError:
            return render(request,"register.html",{'register_errmsg':"注册失败"})
        # 4. 状态保持:注册成功即登陆成功,登陆的本质就是做状态保持
        # login() 默认将状态保持信息写入到浏览器和服务端的数据库(redis:1)
        login(request,user)

        # 5. 响应结果: 注册成功重定向到首页
        # return http.HttpResponse("注册成功")
        # return redirect(reverse("子应用总路由命名空间:子路由命名空间"))
        # return redirect(reverse("contents:index"))

        # 注册成功之后,响应之前,用户名写入到 cookie
        response = redirect(reverse("contents:index"))
        # response.set_cookie("key","value",max_age=3600*24*14)
        response.set_cookie("username", user.username, max_age=3600 * 24 * 14)

        # 响应结果
        return response

'''
查询字符串参数: request.GET
POST表单参数: request.POST
JSON数据: request.body
COOKIES数据: request.COOKIES
文件数据: request.file
请求头: request.META
当前发送请求的用户信息: request.user

'''